<?
/**
* Copyright (c) 2002-2007 BioWare Corp.
* http://www.bigdaddymonitor.org
*
* This file is part of the BigDaddy Monitoring
* program. It is free software distributed under
* the terms of the BSD License. It is ditributed
* in the hopes that it will be useful, but
* WITHOUT ANY WARRANTY; without event the implied
* warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE.
*
* The BSD License is available from:
* http://www.opensource.org/licenses/bsd-license.php
**/
/**
 * Class::UserSession
 * @author Duleepa Wijayawardhana <dups@bioware.com>
 * @version September 2006
 * 
 * Description: Creates a session for the user
 *
 * The following constants contain the information which is made available about the
 * session:
 * LOGGEDIN_USERNAME (string Current Username of the user that is logged in)
 * LOGGEDIN_FULLNAME (string Common name of the user that is logged in)
 */
class UserSession
{
	//Sets whether the session is active or not
    //1 = active
    //0 = inactive
	public $active;
	public $nError;
    
    public $lastActive;
    
    //BaseDN
	private $LDAPbasedn=LDAP_BASEDN; //'OU=Accounts,OU=BioWare,DC=bioware,DC=com';
	
	//LDAP Server
    private $LDAPServer=LDAP_SERVER; //"ldap.bioware.com";
	
	function __construct()
	{
	}
	/*---------------------------------------------------------------------------------
      void SetSession (string username)
      Duleepa Wijayawardhana
      2 October 2005
      
      Sets a BioWare Session
      ---------------------------------------------------------------------------------*/
	function SetSession($sUsername)
	{
		$sql="SELECT username, firstname, lastname, location
			FROM users
			WHERE username='".$sUsername."'
				and active=1";
		$aResult=db_fetch_result(db_query($sql));
		
		if (!is_array($aResult))
		{
			$this->active=0;
			return;
		}
		else
		{
			$this->active=1;
		}
		//Set the required constants
		define ("LOGGEDIN_USERNAME", $aResult["username"]);
		define ("LOGGEDIN_FIRSTNAME", $aResult["firstname"]);
        define ("LOGGEDIN_LASTNAME", $aResult["lastname"]);
		
		
		//set Last_active
        $nLastActive=time();
        $sql="UPDATE users SET
            lastActive = FROM_UNIXTIME(".$nLastActive.")
			WHERE username='".LOGGEDIN_USERNAME."'";
		db_query($sql);
		$this->lastActive = $nLastActive;
		
	}
	
	/*---------------------------------------------------------------------------------
      (bool) AuthenticateMySQL (string username, string password[, bool bNoActiveSet])
      Duleepa Wijayawardhana
      2 October 2005
      
      Authenticates a BiOWare Username and Password. With optional bNoActiveSet, the
      active flag of the session is not interfered with. Instead a true or false
      is returned indicating that the Authentication was successful or not. This is useful
      after the initial authentication when a re-veriofication is required.
      
      This authenticates against MYSQL and not LDAP. Note, if the password field is
      empty for the user account then it is not authenticated
      ---------------------------------------------------------------------------------*/
	public function AuthenticateMySQL($sUsername, $sPassword, $bNoActiveSet=NULL)
	{
		//Clean up credentials
        $sUsername=strtolower($sUsername);
		$sPassword=stripslashes($sPassword);
		
		$sql = "SELECT password FROM users WHERE username = '".$sUsername."' and active=1";
		$aResult=db_fetch_result(db_query($sql));
		
		if (!is_array($aResult))
		{
			if ($bNoActiveSet==1)
			{
				return false;
			}
			
			$this->active=0;
			$this->nError=3;
		}
		
		if ($aResult["password"]=="")
		{
			if ($bNoActiveSet==1)
			{
				return false;
			}
			
			$this->active=0;
			$this->nError=4;
		}
		
		if ($aResult["password"] == md5($sPassword))
		{
			if ($bNoActiveSet==1)
			{
				return true;
			}
			
			$this->active=1;
			return;
		}
		else
		{
			if ($bNoActiveSet==1)
			{
				return false;
			}
			
			$this->active=0;
			$this->nError=5;
		}

	}
    /*---------------------------------------------------------------------------------
      (bool) AuthenticateLDAP (string username, string password[, bool bNoActiveSet])
      Duleepa Wijayawardhana
      2 October 2005
      
      Authenticates a BiOWare Username and Password. With optional bNoActiveSet, the
      active flag of the session is not interfered with. Instead a true or false
      is returned indicating that the Authentication was successful or not. This is useful
      after the initial authentication when a re-veriofication is required.
      ---------------------------------------------------------------------------------*/
	function AuthenticateLDAP($sUsername, $sPassword, $bNoActiveSet=NULL)
	{
		//Clean up credentials
        $sUsername=strtolower($sUsername);
		$sPassword=stripslashes($sPassword);

		//We must connect using the BioWare Common Name for this user
        $sql="SELECT cn FROM users WHERE username='".$sUsername."' and active=1";
		$aResult=db_fetch_result(db_query($sql));
		
		//If we don't have the CN then we cannot connect, fail them.
		if ($aResult["cn"]=="" || !is_array($aResult))
		{
			if ($bNoActiveSet==1)
			{
				return false;
			}
			
			$this->active=0;
			$this->nError=2;
			return;
		}
		
		//Attempt to bind
        $ldapbind = $this->LDAPBind($aResult["cn"], $sPassword);
		
		// verify binding
		if ($ldapbind)
		{
			if ($bNoActiveSet==1)
			{
				return true;
			}
			
			$this->active=1;
			return;
		}
		else
		{
			if ($bNoActiveSet==1)
			{
				return false;
			}
			
			$this->active=0;
			$this->nError=1;
			return;
		}
	}
    /*---------------------------------------------------------------------------------
      res LDAPBind (string $sCN, $sPassword)
      Duleepa Wijayawardhana
      2 October 2005
      
      Returns a LDAP Bind resource based on string Common Name and string Password
      ---------------------------------------------------------------------------------*/
	function LDAPBind($sCN, $sPassword)
	{
		//First connect to the LDAP server
        $ldapconn = ldap_connect($this->LDAPServer);
		if (!$ldapconn)
		{
			die("Fatal: LDAP Server ".$this->LDAPServer." Could Not Be Contacted. Contact SysAdmin");
		}
		
		$ldapbind = @ldap_bind($ldapconn, $sCN, $sPassword);
		
		return $ldapbind;
	}
	/*---------------------------------------------------------------------------------
      void DestroySession ()
      Duleepa Wijayawardhana
      2 October 2005
      
      Destroys a session
      ---------------------------------------------------------------------------------*/
	function DestroySession()
	{
		$this->active=0;
		session_destroy();
		return;
	}
}



?>
